
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;


public class CentralServerHandler implements Runnable{
    private ConcurrentHashMap<Integer, Address> storagePointer;
    private ConcurrentHashMap<Address,Integer> numberOfKeys;
    private final int s = 30;

    public CentralServerHandler(ConcurrentHashMap<Integer, Address> storagePointer, ConcurrentHashMap<Address, Integer> numberOfKeys) {
        this.storagePointer = storagePointer;
        this.numberOfKeys = numberOfKeys;
    }



    public void run(){
         while (true) {
            try {
                try {
                    Thread.sleep(1000 * s);
                } catch (InterruptedException ex) {
                    Logger.getLogger(CentralServerHandler.class.getName()).log(Level.SEVERE, null, ex);
                }

                //Salvar estado do CentralServer em dois ficheiros separados
                ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("backup_storage.dat"));
                out.writeObject(storagePointer);
                out.flush();
                out.close();
                
                out = new ObjectOutputStream(new FileOutputStream("backup_keys.dat"));
                out.writeObject(numberOfKeys);
                out.flush();
                out.close();
                System.out.println("Saved.");

            } catch (IOException es) {
                es.printStackTrace();
            }
        }
    }


}
